package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.dto.activity.ActivityDTO;
import com.qk.entity.Activity;
import com.qk.entity.Clue;
import com.qk.management.mapper.ActivityMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService {

    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ClueMapper clueMapper;

    @Override
    public List<Activity> getActivityByType(String type) {
        return activityMapper.selectByType(type);
    }

    @Override
    public PageResult<ActivityDTO> getActivities(ActivityDTO activityDTO) {
        PageHelper.startPage(activityDTO.getPage(), activityDTO.getPageSize());
        List<ActivityDTO> list = this.baseMapper.selectByPage(activityDTO);
        Page<ActivityDTO> page = (Page<ActivityDTO>) list;
        return PageResult.<ActivityDTO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }

    @Override
    public void deleteActivity(Integer id) {
        List<Clue> clues = clueMapper.selectList(Wrappers.lambdaQuery(Clue.class).eq(Clue::getActivityId, id));
        if (!clues.isEmpty()) {
            CommonException.throwCommonException(ParamEnum.ACTIVITY_REFERENCE_ERROR);
        }
        this.baseMapper.deleteById(id);
    }

    @Override
    public void addActivity(ActivityDTO activityDTO) {
        Activity activity = BeanUtil.copyProperties(activityDTO, Activity.class);
        activity.setCreateTime(LocalDateTime.now());
        activity.setUpdateTime(LocalDateTime.now());
        this.save( activity);
    }

    @Override
    public void updateActivity(ActivityDTO activityDTO) {
        Activity activity = BeanUtil.copyProperties(activityDTO, Activity.class);
        activity.setUpdateTime(LocalDateTime.now());
        this.updateById(activity);
    }
}
